import sys
try:
    from osgeo import ogr
except:
    import ogr

filename = 'shpdata/bou2_4p.shp'
driver = ogr.GetDriverByName('ESRI Shapefile')
dataSource = driver.Open(filename,0)
""":type : osgeo.ogr.DataSource"""
print("Description:",dataSource.GetDescription())
if dataSource is None:
    print ('could not open')
    sys.exit(1)

print("*"*8,"layer","*"*8)
layer = dataSource.GetLayer()
""":type : osgeo.ogr.Layer"""
print("Name:",layer.GetName())
print("RefCount:",layer.GetRefCount())
print("GeomType:",layer.GetGeomType())
print("GeometryColumn:",layer.GetGeometryColumn())
print("FIDColumn:",layer.GetFIDColumn())
print("FeatureCount:",layer.GetFeatureCount())

layerDefn = layer.GetLayerDefn()
""":type : osgeo.ogr.FeatureDefn"""
for i in range(layerDefn.GetFieldCount()):
    fieldDefn = layerDefn.GetFieldDefn(i)
    """:type : osgeo.ogr.FieldDefn"""
    fieldname = fieldDefn.GetName()
    fieldtype = fieldDefn.GetType()
    fieldtypename = fieldDefn.GetTypeName()
    fieldtypename2 = fieldDefn.GetFieldTypeName(1)
    fieldtypename3 = fieldDefn.GetFieldTypeName(20)
    print("Fieldname:",fieldname)
    print("Fieldtype:",fieldtype)
    print("Fieldtypename:",fieldtypename)
    print("Fieldtypename:",fieldtypename2)
    print("Fieldtypename:",fieldtypename3)

print("*"*8,"feature","*"*8)
feat = layer.GetFeature(74)
""":type : osgeo.ogr.Feature"""
print("FID:",feat.GetFID())
print("DefnRef:",feat.GetDefnRef()) # TODO 查看它的所有属性
print("FieldCount:",feat.GetFieldCount())
field = feat.GetField(1)
print(field)
print("GeomFieldCount:",feat.GetGeomFieldCount())
print("GeometryRef:",feat.GetGeometryRef())
print("*"*8,"geom","*"*8)
geom = feat.GetGeometryRef()
""":type : osgeo.ogr.Geometry"""
print(geom.ExportToJson())
print(geom.ExportToWkt())

